/**
 * Created by Dalyn on 2017/3/28.
 */
import React from "react";
import Relay from "react-relay";
import getGoodsCatalogMutation from "./mutation/GetGoodsCatalogMutation"
import Confirm from "../../common/Confirm"
import InputBox from "../../common/InputBox"
import ReactKey from "../../util/ReactKey"
import BatchHint from "./BatchHint"
import "./css/product.css";
import Product_item from "./Product_item"
import GetGoodsImportMutation from "./mutation/GetGoodsImportMutation";
import ImportGoodsMutation from "./mutation/ImportGoodsMutation";

/*导出组件*/
export default class ProductImport extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            /*参数*/
            level: "1",
            token: "",
            name: "",
            levelId: "0",
            /*产品id*/
            productId: "0",
            parenId: "",
            /*产品字段*/
            goodsProperty: "",
            goodsInfoDescModelList: [],

            /*一级分类*/
            firstLevel: [],
            /*二级分类*/
            secondLevel: [],

            /*产品信息参数*/
            categoryId: "13",

            /*请求参数错误提示*/
            hint: "",
            /*操作成功提示*/
            successHint: true,
            /*页码*/
            pageNum:1,
            /*总条数*/
            totalResult:""
        };
        this.categoryId="0";
        this.categoryIdSender="13";
        this.defaultSecondId = "0";

        /*当前页条数*/
        this.pageItem="";

        /*每页条数*/
        this.pageSize=10;
        this.pageNum = 1;

        /*一级选中*/
        this.isFirst=0;
        /*二级选中*/
        this.isSecond=0;
        /**
         * 选中的产品ids
         * @type {Array}
         */
        this.productIds="";
        /**
         * 搜索的产品名
         * @type {string}
         */
        this.productName="";

        this.checkedFlag = false;
        this.ratio = "";
        this.dayRate = "";
        this.style = {
            confirm1: {
                width: '85px',
                height: '30px',
                backgroundColor: "#36b3b3",
                fontSize: "16px",
                color: "#fff",
                marginTop: "16px",
                marginLeft: "20px",
                fontFamily: "Microsoft YaHei",
                borderRadius: "30px"
            },
            confirm2: {
                width: '85px',
                height: '30px',
                backgroundColor: "#A9A9A9",
                fontSize: "16px",
                color: "#fff",
                marginTop: "16px",
                marginLeft: "20px",
                fontFamily: "Microsoft YaHei",
                borderRadius: "30px"
            },
            search: {
                width: '85px',
                height: '30px',
                backgroundColor: "#36b3b3",
                fontSize: "16px",
                color: "#fff",
                // marginTop: "16px",
                marginLeft: "20px",
                fontFamily: "Microsoft YaHei",
                borderRadius: "8px"
            },
            set: {
                width: '60px',
                height: '27px',
                backgroundColor: "#fab955",
                fontSize: "16px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius: "3px",
                marginLeft: "15px"
            },
            company: {
                width: "200px",
                height: "30px",
                // borderColor: "#bbbbbb",
                // marginTop: "15px"
            },
            page_ensure: {
                width: '39px',
                height: '19px',
                backgroundColor: "white",
                border: '1px solid #e7e6e6',
                borderRadius: '2px',
                color: "#999"
            }
        };
        this.propertyMapper = {
            productName:"品名",
            constituent:"成分",
            yarn:"纱支",
            gramWeight:"克重",
            fabricWeave:"织物组织",
            density:"密度",
            larghezza:"门幅/幅宽",
            washingProcess:"水洗工艺",
            dyeingProcess:"印染工艺",
            ranzhengProcess:"染整工艺",
            weftYarn:"经纬纱",
            structure:"组织结构",
            shrinkage:"缩水率",
            networkType:"成网方式",
            breed:"品种",
            season:"适用季节",
            designProcess:"花型工艺",
            printingStyle:"印花风格",
            fashionElement:"流行元素",
            weight:"重量",
            flowerColor:"花色",
            specification:"规格",
            thickness:"厚度",
            high:"毛高",
            yarnTypes:"纱线类型",
            yarnState:"成纱状态",
            colour:"颜色",
            prickle:"计量单位",
            pattern:"图案",
            styleNo:"款号",
            productType:"产品类别",
            style:"风格",
            function:"功能",
            fabric:"面料",
            design:"款式",
            productCode:"货号",
            purpose:"用途",
            remarks:"备注",
        };
        this.ischoseid = [];
    }

    /*分类请求*/
    levelRelay(categoryId,level) {
        Relay.Store.commitUpdate(
            new getGoodsCatalogMutation({
                categoryId:categoryId,
                level:level
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let errorCode = response.getGoodsCatalog.responseData.errorCode;
                    let goodsCataLogSecond = [];
                    if(errorCode==0){
                        if (categoryId!=undefined && categoryId !=0){
                            goodsCataLogSecond = response.getGoodsCatalog.responseData.goodsInfoCatalogModelList;
                            this.setState({
                                secondLevel:goodsCataLogSecond
                            });
                            this.defaultSecondId = goodsCataLogSecond[0].categoryId;
                            this.productInfoRelay(this.defaultSecondId);
                            return;
                        }
                        let goodsCatalog = response.getGoodsCatalog.responseData.goodsInfoCatalogModelList;
                        this.setState({
                            firstLevel:goodsCatalog
                        });

                    }else if (level == 1){
                        this.productInfoRelay(this.categoryIdSender);
                        this.setState({
                            secondLevel:[],
                        });
                        this.isSecond=0;
                    }
                }

            }
        );
    }

    /*产品信息请求*/
    productInfoRelay(categoryIdSender) {
        Relay.Store.commitUpdate(
            new GetGoodsImportMutation({
                pageSize: this.pageSize,
                pageNum: this.state.pageNum,
                categoryId: categoryIdSender,
                productName: this.productName,
                goodsId: this.state.productId,
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    // alert(this.categoryId);
                    let data = response.getImportGoodsListBackstage.responseData;
                    // console.log(data);
                    if (data.errorCode === "0") {
                        this.pageItem = data.goodsInfoDescModelList.length;
                        this.refs._selectAll.checked = false;
                        this.setState({
                            totalResult:data.totalResult,
                            goodsProperty: data.goodsProperty,
                            goodsInfoDescModelList: data.goodsInfoDescModelList,
                        });
                    } else {
                        this.setState({
                            hint: data.value,
                            goodsProperty: data.goodsProperty,
                            goodsInfoDescModelList:[]
                        });
                    }
                }

            }
        );
    }

    doImportProduct(ids){
        Relay.Store.commitUpdate(
            new ImportGoodsMutation({
                ids: ids
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let data = response.importGoodsBackstage.responseData;

                    if (data.errorCode === "0") {
                        this.productInfoRelay(this.categoryIdSender);
                        this.productIds = [];
                        let message = "导入成功！";
                        this.refs.batchHint.showWindow(true,message);
                    }
                }
            }
        );
    }

    /*默认请求*/
    componentWillMount() {
        /*一级分类*/
        this.levelRelay();
        /*默认显示产品信息*/
        this.productInfoRelay(this.categoryIdSender);
    }

    /*添加级别类型*/
    firstLevel() {
        return this.state.firstLevel.map((item, index) => {

            return <Confirm key={ReactKey.key}
                            style={this.isFirst === index ? this.style.confirm1 : this.style.confirm2}
                            tcontext={item.name} touch={this.onCheckedLevel.bind(this,index,item.categoryId,item.level)} ref={item.name}/>
        })
    }

    secondLevel() {
        return this.state.secondLevel.map((item, index) => {
            return <Confirm key={ReactKey.key}
                            style={this.isSecond == index ? this.style.confirm1 : this.style.confirm2}
                            tcontext={item.name} touch={this.onCheckedSecondLevel.bind(this,index,item.categoryId,item.level)} ref={item.name}/>
        })
    }

    /*点击商品类型*/
    onCheckedLevel(indexchose,categoryId,level) {
        this.pageInit();
        this.setState({
            categoryId:categoryId
        });
        this.isFirst=indexchose;
        this.isSecond=0;
        this.categoryId=categoryId;
        this.categoryIdSender=categoryId;
        this.productName="";
        this.levelRelay(categoryId,level);
        // this.productInfoRelay( this.categoryIdSender);

    }
    onCheckedSecondLevel(indexchose,categoryId,level) {
        this.pageInit();
        this.setState({
            categoryId:categoryId
        });
        this.isSecond = indexchose;
        this.categoryId=categoryId;
        this.categoryIdSender=categoryId;
        this.levelRelay(categoryId,level);
        this.productInfoRelay(this.categoryIdSender);
    }

    /*模糊搜索*/
    search() {
        this.productName = this.refs.search.state.text;
        this.setState({
            pageNum : 1
        },()=>this.productInfoRelay(this.categoryIdSender));
    }

    doSearch(){

    }
    /*点击全选*/
    selectAll() {
        let isChecked = this.refs._selectAll.checked;
        this.state.goodsInfoDescModelList.map((item, index) => {
            this.refs[index + 'product_item'].refs._radioBtn.checked = isChecked;
        });
    }

    /*点击一个checkbox--全选按钮false*/
    isallclick(isSelectAll) {
        this.refs._selectAll.checked = isSelectAll;
    }


    /**
     * 商品导入
     */
    importProduct(){

        let length = this.state.goodsInfoDescModelList.length;

        for (var i = 0; i<length ;i++){
            if(this.refs[i + 'product_item'].refs._radioBtn.checked){
                let productId = this.refs[i + 'product_item'].props.goodsItem.goodsId;
                this.productIds = this.productIds+productId+",";
            }
        }

        if(this.productIds.length === 0){
            let  message = "请勾选要操作的对象！";
            this.refs.batchHint.showWindow(true,message);

            return;
        }

        //发起导入请求
        this.doImportProduct(this.productIds);
    }

    /*产品信息列表 表头*/
    goodsInfoListTitle() {
        let goodsProperty = this.state.goodsProperty.split(",");
        return goodsProperty.map((item, index) => {
            return (
                <span className="product_set_bor product_set_ts2" style={{width:(1016-goodsProperty.length)/(goodsProperty.length)+"px"}}
                      key={ReactKey.key}>{this.propertyMapper[item]}</span>
            )
        })
    }

    /*产品信息列表-内容*/
    addList() {
        return this.state.goodsInfoDescModelList.map((item, index) => {
            return (
                <Product_item ref={index + 'product_item'} goodsItem={item} index={index} goodsProperty={this.state.goodsProperty}
                              _isallclick={this.isallclick.bind(this)}
                              key={ReactKey.key}/>
            )
        })
    }

    /*页面表单失去焦点时*/
    bluron(type) {
        switch (type) {
            case "search":

                return;
            case "page":{
                let pageNum = this.refs.page.value;

                if(pageNum<1 || pageNum > this.pageTotal() || this.refs.page.value == ""){
                    this.setState({
                        pageNum:this.pageNum
                    });
                }
                return;
            }
        }
    }

    /*获取焦点*/
    focuson(type) {
        switch (type) {
            case "search":
                this.setState({
                    hint: ""
                });
                return;
        }
    }

    /**
     * 点击产品类型的时候重置页码
     */
    pageInit(){
        this.pageNum=1;
        this.setState({
            pageNum:1,
            totalResult:0,
            hint:""
        });
        this.pageItem = 0;
        this.refs.search.setState({text:""});
    }

    /*页码*/
    page() {
        let pageTotal = this.pageTotal();
        let pageNum = this.state.pageNum;
        if (pageNum < 1) {
            this.pageNum=1;
            this.setState({
                pageNum:1
            },()=>this.productInfoRelay(this.categoryIdSender));
            return;
        }
        if (pageNum > pageTotal) {
            this.pageNum=pageTotal;
            this.setState({
                pageNum:pageTotal
            },()=>this.productInfoRelay(this.categoryIdSender));
            return
        }
        this.pageNum=pageNum;
        this.setState({
            pageNum:pageNum
        },()=>this.productInfoRelay(this.categoryIdSender));
    }


    /**/
    changePageNum(e) {
        let numtest = /^[0-9]*$/;
        let text = e.target.value;
        if (!numtest.test(text)) {
            return;
        }
/*
        if(text<1 || text > this.pageTotal())
            return;*/

        this.setState({
            pageNum:text
        });
    }

    /*总页数*/
    pageTotal() {
        return Math.ceil(this.state.totalResult / this.pageSize)
    }

    /*上一页*/
    leftBtn() {
        let pageNum = this.state.pageNum;
        if (pageNum <= 1) {
            return;
        } else {
            pageNum--;
            this.pageNum = pageNum;
            this.setState({
                pageNum:pageNum
            },()=>this.productInfoRelay(this.categoryIdSender));
        }
        //  this.productInfoRelay(this.categoryIdSender);
    }

    /*下一页*/
    rightBtn() {
        let pageTotal = this.pageTotal();
        let pageNum = this.state.pageNum;
        if (pageNum >= pageTotal) {
            return;
        } else {
            pageNum++;
            this.pageNum = pageNum;
            this.setState({
                pageNum:pageNum
            },()=>this.productInfoRelay(this.categoryIdSender));

            // this.productInfoRelay(this.categoryIdSender);
        }
    }

    render() {
        return (
            <div className="product_set">
                <p className="product_set_nav1">产品管理 > <span className="product_set_nav2">未导入产品</span></p>
                <div className="product_set_box">
                    <p className="product_set_title">
                        <i className="product_set_tLine"></i>
                        <span className="product_set_tText">产品分类</span>
                    </p>
                    <p className="product_set_tab">一级分类：
                        {
                            this.firstLevel()
                        }
                    </p>
                    <p className="product_set_tab">二级分类：
                        {
                            this.secondLevel()
                        }
                    </p>
                    {/*搜索*/}
                    <div className="product_set_search clear">
                        <div className="product_set_searchInp">
                            <InputBox titletext={'品名：'} space={20} style={this.style.company} defaultvalute="请输入品名"
                                      maxlength={30} ref={'search'} bluron={this.bluron.bind(this, "search")}
                                      focuson={this.focuson.bind(this, "search")}/>
                        </div>
                        <div className="product_set_searchBtn">
                            <Confirm style={this.style.search} tcontext={'搜索'} touch={this.search.bind(this)}/>
                            <span className="product_set_searchHint">{this.state.hint}</span>
                        </div>
                    </div>
                    {/*列表*/}
                    <ul className="product_set_ul">
                        <li className="product_set_t">
                            <span className="product_set_tsp1">符合条件的产品共{this.state.totalResult ? this.state.totalResult : "0"}条</span>
                            <div className="product_set_bombBtn">
                                <span className="product_set_tsp2" onClick={this.importProduct.bind(this)}>导入产品</span>
                            </div>

                            <BatchHint ref={"batchHint"}/>
                            {/* <ProductEdit ref={"productEdit"} goodsProperty={this.state.goodsProperty}/>*/}
                        </li>
                        <li className="product_set_th">
                            <span className="product_set_nor product_set_ts0">
                                <input className="product_set_cb" type="checkbox"
                                       ref={"_selectAll"}
                                       onChange={this.selectAll.bind(this)}/>
                            </span>
                            <span className="product_set_nor product_set_ts1">序号</span>
                            {this.goodsInfoListTitle()}
                           {/* <span className="product_set_nor product_set_ts1" style={{borderRight: "none"}}>查看</span>*/}
                        </li>
                        {
                            this.addList()
                        }
                    </ul>
                    {/*页码*/}
                    <div className="product_page clear">
                        <ol className="product_page_ol clear">
                            <li className="product_page_oli1">
                                总计<span>{this.state.totalResult ? this.state.totalResult : "0"}</span>条
                            </li>
                            <li className="product_page_oli2">
                                本页<span>{this.pageItem ? this.pageItem : "0"}</span>条
                            </li>
                            <li className="product_page_oli3">
                                共<span>{this.pageTotal()}</span>页
                            </li>
                            <li>第&nbsp;&nbsp;<input type="text" className="product_page_olinp" ref={"page"}
                                                    value={this.state.pageNum} onBlur={this.bluron.bind(this, "page") }
                                                    onChange={this.changePageNum.bind(this)}/>&nbsp;&nbsp;页
                            </li>
                            <li><Confirm tcontext={'确定'} style={this.style.page_ensure} touch={this.page.bind(this)}/>
                            </li>
                            <li className="product_page_olbtn">
                                <i className="product_page_button product_page_left"
                                   onClick={this.leftBtn.bind(this)}></i>
                                <i className="product_page_button product_page_right"
                                   onClick={this.rightBtn.bind(this)}></i>
                            </li>
                        </ol>
                    </div>
                    {/*/!*操作成功提示*!/*/}
                    <div className="settle_success_bg"
                         style={this.state.successHint ? {display: 'none'} : {display: 'block'}}></div>
                </div>
            </div>
        )
    }
}